package com.yifei.filter;


import com.yifei.model.enums.ResultCode;
import com.yifei.utils.JwtUtil;
import com.yifei.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 验证码过滤器
 * @Author: yiFei
 * @date: 2023/9/24 19:52
 */
@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = jwtUtil.resolveToken(request);
        try {
            // 判断是否存在 token ，不存在就直接放行
            if (StringUtils.hasText(token)) {
                // 获取权限信息
                Authentication auth = jwtUtil.getAuthentication(token);
                // 如果没有权限信息，表示 token 不是本地颁发的
                if (ObjectUtils.isEmpty(auth)) {
                    ResponseUtil.writeErrMsg(response, ResultCode.TOKEN_INVALID);
                    return;
                }
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
        } catch (Exception e) {
            SecurityContextHolder.clearContext();
            ResponseUtil.writeErrMsg(response, ResultCode.ACCESS_UNAUTHORIZED);
            return;
        }

        filterChain.doFilter(request, response);
    }
}
